//
//  NetService.swift
//  kano
//
//  Created by Frank on 2024/9/6.
//

import Foundation
import UIKit

let badNetWorking = "Your network is not working!"

class NetService {
    
    static func ka_serviceConfig() {
//        loginProvider.request(.getConfig) { result in
//            switch result {
//            case .success(let response):
//                if response.statusCode == 200 {
//                    guard let responseString = String(data: response.data, encoding: .utf8) else {return}
//                    guard let data = responseString.data(using: .utf8) else {return}
//                    do {
//                        let responseObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
//                        if let arrayResponse = responseObject as? Dictionary<String, String> {
//                            if arrayResponse.count > 0 {
//                                let newValue = arrayResponse["d"]
//                                UserDefaults.standard.setValue(newValue, forKey: "kConfig")
//                            }
//                        }
//                        //                        if let arrayResponse = responseObject as? [Any] {
//                        //                            if let first = arrayResponse.first as? Dictionary<String, String> {
//                        //                                let newValue = first["realm"]
//                        //                                UserDefaults.standard.setValue(newValue, forKey: "kConfig")
//                        //                            }
//                        //                        }
//                    } catch {return}
//                }
//            case .failure(let error):
//                
//                print(error.localizedDescription)
//            }
//        }

        
//        let paraDic = [
//            "softwareUpdateVersions":KAUserManager.shared.user.softwareUpdateVersions,
//            "positionOrder": KAUserManager.shared.user.positionOrder,
//            "customerIdentification": UIDevice.ka_UUID,
//            "uniqueUserIdentifier" : UIDevice.ka_UUID
//        ]
//        loginProvider.request(.autoLogin(paraDic)) { result in
//            switch result {
//            case .success(let response):
//                if response.statusCode == 200 {
//                    NetResponse<KAUser>.handleResponseData(response.data) { isSuccess, message, response in
//                        if !isSuccess {
//                            KAUserManager.shared.userLogout()
//                        } else {
//                            //other operation
//                            KAReport.ka_reportWith(type: .device)
//                            //登录成功
//                            KAAFTool.logEvent(event: "SKP_Success_Login")
//                        }
//                    }
//                }
//            case .failure(let error):
//                print(error.localizedDescription)
//            }
//        }

        loginProvider.request(.checkService()) { result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    guard let responseString = String(data: response.data, encoding: .utf8) else {
                        ka_requestConfig()
                        return
                    }
                    guard let data = responseString.data(using: .utf8) else {
                        ka_requestConfig()
                        return
                    }
                    do {
                        let responseObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
                        if let arrayResponse = responseObject as? Dictionary<String, String> {
                            if arrayResponse.count > 0 {
                                guard let newValue = arrayResponse["d"] else {
                                    ka_requestConfig()
                                    return
                                }
                                UserDefaults.standard.setValue(newValue, forKey: "kConfig")
                                KAUserManager.shared.netUseFul = true
                                autoLogin()
                            } else {
                                ka_requestConfig()
                            }
                        } else {
                            ka_requestConfig()
                        }
                    } catch {
                        ka_requestConfig()
                        return
                    }
                } else {
                    ka_requestConfig()
                    return
                }
            case .failure(let error):
                //主域名不可用，需请求远端地址
                ka_requestConfig()
                print(error.localizedDescription)
            }
        }
    }
    
    static func ka_requestConfig() {
        loginProvider.request(.getConfig) { result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    guard let responseString = String(data: response.data, encoding: .utf8) else {
                        KAUserManager.shared.netUseFul = false
                        return
                    }
                    guard let data = responseString.data(using: .utf8) else {
                        KAUserManager.shared.netUseFul = false
                        return
                    }
                    do {
                        let responseObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
                        if let arrayResponse = responseObject as? Dictionary<String, String> {
                            if arrayResponse.count > 0 {
                                guard let newValue = arrayResponse["d"] else {
                                    KAUserManager.shared.netUseFul = false
                                    return
                                }
                                UserDefaults.standard.setValue(newValue, forKey: "kConfig")
                                KAUserManager.shared.netUseFul = true
                            } else {
                                KAUserManager.shared.netUseFul = false
                            }
                        } else {
                            KAUserManager.shared.netUseFul = false
                        }
                    } catch {
                        KAUserManager.shared.netUseFul = false
                        return
                    }
                } else {
                    KAUserManager.shared.netUseFul = false
                    return
                }
            case .failure(let error):
                KAUserManager.shared.netUseFul = false
                print(error.localizedDescription)
            }
            autoLogin()
        }
    }
    
    static func autoLogin() {
        let paraDic = [
            "softwareUpdateVersions":KAUserManager.shared.user.softwareUpdateVersions,
            "positionOrder": KAUserManager.shared.user.positionOrder,
            "customerIdentification": UIDevice.ka_UUID,
            "uniqueUserIdentifier" : UIDevice.ka_UUID
        ]
        loginProvider.request(.autoLogin(paraDic)) { result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAUser>.handleResponseData(response.data) { isSuccess, message, response in
                        if !isSuccess {
                            KAUserManager.shared.userLogout()
                        } else {
                            //other operation
                            KAReport.ka_reportWith(type: .device)
                            //登录成功
                            KAAFTool.logEvent(event: "SKP_Success_Login")
                        }
                    }
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    static func ka_loginWith(mobile: String, password: String, codeToken: String, operationType: KAOperation, verifyCode: String, verifyToken: String,captchaCode: String, captchaId: String, secondLogin: Int, deviceFirstLogin: Bool = false, handler:@escaping NetHandler<KAUser>) {
        let mobile = KAUserManager.shared.user.notificationMessage
        var paraDic: [String : Any] = [
            "notificationMessage":mobile,
            "reversedContactNumber":mobile,
            "previousRate":password,
            "authenticationToken":codeToken,
            "uniqueUserIdentifier":UIDevice.ka_UUID,
            "customerIdentification":UIDevice.ka_UUID,
            "loginMethod": "0",
            "secondaryLogin": secondLogin,
            "initialLoginEvent": KAUserManager.shared.appIsFirstLaunched(mobile),
            "processActionType": 0,
            "authCodeForTransaction": operationType.rawValue,
            "invitationco": verifyCode,
            "passwordSetupStatus": 1,
            "userGoogleIdentifier":"",
            "tadpoleLoanDeduction": "",
//            "imageCodeVerification": captchaCode.isEmpty ? false : true,
        ]
        if operationType == .Register {
            paraDic.updateValue(1, forKey: "verificationRequirement")
            paraDic.updateValue(verifyCode, forKey: "validityStartTime")
            paraDic.updateValue(verifyToken, forKey: "authorizationco")
        }
        if !captchaCode.isEmpty {
            paraDic.updateValue(true, forKey: "imageCodeVerification")
            paraDic.updateValue(captchaCode, forKey: "securityCode")
            paraDic.updateValue(captchaId, forKey: "renewalRepaidCapital")
        }
        UIViewController.ka_current().view.showLoading()
        loginProvider.request(.login(paraDic)) { result in
            UIViewController.ka_current().view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAUser>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let user = response?.voucherQuantity else { return }
                            let defaultUser = KAUserManager.shared.user
                            var newUser = defaultUser.merge(with: user)
                            newUser.notificationMessage = KAUserManager.shared.user.notificationMessage
                            KAUserManager.shared.user = newUser
                            
                            if deviceFirstLogin == false {
                                KAUserManager.shared.userLogin(with: newUser.notificationMessage)
                            }

                            handler(isSuccess,message, response)
                        } else {
                            handler(isSuccess,message, response)
                        }
                    }
                }else {
                    handler(false, badNetWorking, nil)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    static func ka_checkMobileWith(mobile: String, handler:@escaping NetHandler<KAUser>) {
        let paraDic = [
            "notificationMessage":KAEncrypt.ka_encrypt(mobile), "uniqueUserIdentifier":UIDevice.ka_UUID, "reversedContactNumber":mobile
        ]
        UIViewController.ka_current().view.showLoading()
        loginProvider.request(.checkMobile(paraDic)) { result in
            UIViewController.ka_current().view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAUser>.handleResponseData(response.data) { isSuccess, message, response in
                        handler(isSuccess,message, response)
                    }
                }else {
                    handler(false, badNetWorking, nil)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    //codeToken校验手机号接口返回；captchaCode图片验证码接口返回；
    static func ka_sentCode(withType codeType: String, codeToken: String, operationType:KAOperation, captchaCode: String = "", newMobile: String = "", handler:@escaping NetHandler<KAContent>) {
        let phoneNM = newMobile.isEmpty ? KAUserManager.shared.user.notificationMessage : newMobile
        let paramDic: [String: Any] = [
            "notificationMessage": phoneNM,
            "channelClassification": codeType,
            "authenticationToken": codeToken,
            "processActionType": operationType.rawValue,
            "visualSecurityCheckCode": captchaCode,
            "imageRecordId": "",
            "userIPAddress": "",
            "relatedSubLoans": "",
            "geetestSecurityChallenge": "",
            "geetestValidationResult": "",
            "targetAuthentication": "",
            "userInvitationRelationId": "",
            "softwareUpdateVersions": "",
            "reversedContactNumber": "",
            "lightPackageIdentifier": "",
            "tokenUpdateTimestamp": ""
        ]
        UIViewController.ka_current().view.showLoading()
        loginProvider.request(.sendCode(paramDic)) { result in
            UIViewController.ka_current().view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAContent>.handleResponseData(response.data) { isSuccess, message, response in
                        handler(isSuccess,message, response)
                    }
                }else {
                    handler(false, badNetWorking, nil)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
        
    }
    
    static func ka_checkPictureCode(captchaId: String, captchaCode: String, handler:@escaping NetHandler<KAContent>) {
        UIViewController.ka_current().view.showLoading()
        let paraDic = [
            "renewalRepaidCapital":captchaId, "pictureVerifyCode":captchaCode,
        ]
        loginProvider.request(.checkPictureCode(paraDic)) { result in
            UIViewController.ka_current().view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAContent>.handleResponseData(response.data) { isSuccess, message, response in
                        handler(isSuccess,message, response)
                    }
                }else {
                    handler(false, badNetWorking, nil)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    static func ka_reportWith(param: Dictionary<String, Any>? = nil, handler: NetHandler<KAContent>? = nil) {
        var array: [[String: Any]] = []
        array.append(param!)
        reportProvider.request(.report(array)) { result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAContent>.handleResponseData(response.data) { isSuccess, message, response in
                        //                        handler(isSuccess,message, response)
                        print("Report Success: \(param!["internationalMobileSubscriberIdentity"]!)")
                    }
                }else {
                    //                    handler(false, badNetWorking, nil)
                    print("Report Fail: \(param!["internationalMobileSubscriberIdentity"]!)")
                    ka_reportWith(param: param, handler: nil)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    static func ka_reportSubChannel(handler: NetHandler<KAContent>? = nil) {
        let paraDic = [
            "softwareUpdateVersions":KAUserManager.shared.user.softwareUpdateVersions,
            "emergencyContactsList": KAAFTool.channel()
        ]
        print("-----: \(KAAFTool.channel())")
        reportProvider.request(.subchannel(paraDic)) { result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAContent>.handleResponseData(response.data) { isSuccess, message, response in
                        //                        handler(isSuccess,message, response)
                        print("Report Success: SubChannel")
                    }
                }else {
                    //                    handler(false, badNetWorking, nil)
                    print("Report Fail: SubChannel")
                    ka_reportSubChannel()
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    
    static func ka_requestHomeInfo(handler:@escaping NetHandler<KAHomeInfo>) {
        let paraDic: [String : Any] = [
            "softwareUpdateVersions": KAUserManager.shared.user.softwareUpdateVersions,
            "contentText" : 0
        ]
        loginProvider.request(.homeInfo(paraDic)) { result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAHomeInfo>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.voucherQuantity else { return }
                            if (content.marketPromotion == 1) {
                                //用户首次授信成功
                                KAAFTool.logEvent(event: "SKP_Firstsuccessfulcredit_extension")
                            }
                            if (content.actionButtonStyle == 1) {
                                //首次获取额度成功
                                KAAFTool.logEvent(event: "SKP_Successfullyobtained_creditfirst")
                            }
                            KADBDBManager.ka_saveInDocument(object: content.kj.JSONString(), fileName: "homeInfo")
                        }
                        handler(isSuccess,message, response)
                    }
                }else {
                    handler(false, badNetWorking, nil)
                }
            case .failure(let error):
//                handler(false, badNetWorking, nil)
                print(error.localizedDescription)
            }
        }
    }
    
    class func ka_requestHomeStatus(handler:@escaping NetHandler<KAAuditState>) {
        let paramDic: [String : Any] = [
            "softwareUpdateVersions": KAUserManager.shared.user.softwareUpdateVersions,
        ]
        loginProvider.request(.creditStatus(paramDic)) { result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAAuditState>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.voucherQuantity else { return }
                            KADBDBManager.ka_saveInDocument(object: content.kj.JSONString(), fileName: "auditStatus")
                        }
                        handler(isSuccess,message, response)
                    }
                }else {
                    handler(false, badNetWorking, nil)
                }
            case .failure(let error):
//                handler(false, badNetWorking, nil)
                print(error.localizedDescription)
            }
        }
    }
    //筛选可用的产品
    class func getActiveProduct(content: KAHomeInfo) -> KAProductInfo? {
        guard content.verificationToken!.count > 0 else {return nil}
        
        let list:[KAProductInfo] = content.verificationToken!
        var normalLoan: KAProductInfo?
        var largeLoan: KAProductInfo?
        _ = list.map {
            // 14days小额，蝌蚪贷也是小额类型
            if ($0.productClassification == 1) {
                normalLoan = $0;
            }
            // Large installment
            if ($0.productClassification == 2) {
                largeLoan = $0;
            }
        }
        if (normalLoan != nil && largeLoan == nil){
            return normalLoan
        }
        if (normalLoan == nil && largeLoan != nil){
            return largeLoan
        }
        if (normalLoan != nil && largeLoan != nil) {
            let largeAmount = largeLoan!.loanInterestPercentage;
            let smallAmount = normalLoan!.loanInterestPercentage;
            let maxCreditLine = max(largeAmount, smallAmount);
            
            // borrowingLoanType 0:无在借订单  1:短贷  2:大额分期
            if (smallAmount > 0 && largeAmount > 0) {
                if (content.loanTypeForBorrowing == 0) {
                    let smallBorrowAmount = normalLoan!.borrowingCapacity;
                    let largeBorrowAmount = largeLoan!.borrowingCapacity;
                    largeLoan!.loanInterestPercentage = maxCreditLine;
                    largeLoan!.borrowingCapacity = max(largeBorrowAmount, smallBorrowAmount);
                    return largeLoan
                }
                if (content.loanTypeForBorrowing == 2) {
                    largeLoan!.loanInterestPercentage = maxCreditLine;
                    return largeLoan
                }
                if (content.loanTypeForBorrowing == 1) {
                    normalLoan!.loanInterestPercentage = maxCreditLine;
                    return normalLoan
                }
            }
            if (largeAmount > 0) {
                return largeLoan
            }
            if (smallAmount > 0) {
                return normalLoan
            }
            if (normalLoan!.loanInterestPercentage == 0 && largeLoan!.loanInterestPercentage == 0) {
                return largeLoan
            }
        }
        return list.first
    }
    
    class func applyAuto(borrowingLoanType: Int, _ couponId: String = "", handler:@escaping NetHandler<KAApply>) {
        let paramDic: [String : Any] = [
            "softwareUpdateVersions" : KAUserManager.shared.user.softwareUpdateVersions,
            "productClassification" : 1,
            "creditAcquisitionStatus" : "0",
            "paginationId" : "index",
            "overdueRateFirstDay" : 0,
            "endTimeValidity" : 0,
        ]
        UIViewController.ka_current().view.showLoading()
        applyProvider.request(.applyAuto(paramDic)) { result in
            UIViewController.ka_current().view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAApply>.handleResponseData(response.data) { isSuccess, message, response in
                        handler(isSuccess,message, response)
                        if !isSuccess { UIViewController.ka_current().view.makeToast(message); return }
                        guard let apply = response?.voucherQuantity else { return }
                        //Under review: 1  Credit failure:-1  Credit success: 2
                        if apply.creditCondition == 1 {
                            UIViewController.ka_current().navigationController?.pushViewController(KAApplyResultVC(reviewResult: .reviewing), animated: true); return
                        }
                        if apply.creditCondition == -1 {
                            UIViewController.ka_current().navigationController?.pushViewController(KAApplyResultVC(reviewResult: .fail), animated: true); return
                            
                            //当天拒绝贷款
                            KAAFTool.logEvent(event: "SKP_Refusingloan_sameday")
                            
                        }
                        if apply.creditCondition != 2 {
                            let infoVC = KAInfoVC(model: apply)
                            UIViewController.ka_current().navigationController?.pushViewController(infoVC, animated: true); return
                        }
                        
                        guard let json = KADBDBManager.ka_getObject(by: "homeInfo") as? String  else {return}
                        let homeInfo = json.kj.model(KAHomeInfo.self)
                        
                        //大额
                        if homeInfo?.subLogicIndicator == 1 {
                            //被拒绝
                            if (apply.creditTiming == "1" || apply.creditTiming == "3") && apply.installationRejectionFlag == "1" {
                                //当天拒绝贷款
                                KAAFTool.logEvent(event: "SKP_Refusingloan_sameday")
                                
                                UIViewController.ka_current().navigationController?.pushViewController(KAApplyResultVC(reviewResult: .fail), animated: true)
                            } else {
                                self.showFlutter(borrowingLoanType: borrowingLoanType, couponId: couponId)
                            }
                        } else {
                            //小额、蝌蚪贷
                            switch apply.creditTiming {
                                //被拒绝
                            case "1": fallthrough
                            case "3":
                                //当天拒绝贷款
                                KAAFTool.logEvent(event: "SKP_Refusingloan_sameday")
                                
                                UIViewController.ka_current().navigationController?.pushViewController(KAApplyResultVC(reviewResult: .fail), animated: true)
                                //审核中
                            case "8": fallthrough
                            case "10":
                                UIViewController.ka_current().navigationController?.pushViewController(KAApplyResultVC(reviewResult: .reviewing), animated: true)
                            default:
                                //去借款
                                self.showFlutter(borrowingLoanType: borrowingLoanType, couponId: couponId)
                            }
                        }
                        
                    }
                }else {
                    handler(false, badNetWorking, nil)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    class func showFlutter(borrowingLoanType: Int, couponId: String = "") {
        var route: String = "/loan"
        if !couponId.isEmpty {
            route = "/loan?voucherGid=\(couponId)"
        }
        KAFlutterManager.showFlutterVC(route: route, parameter: ["borrowingLoanType" : borrowingLoanType, "mobile" : KAUserManager.shared.user.notificationMessage])
    }
}
